<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Encryption</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
    </script>
    <script src="/js/jsencrypt.js"></script>
    <script src="/js/cryptojs.js"></script>
    <script>
        //aesUtil
        /**
         * 简单封装一下
         */
        var aesUtil = {
            //获取key，
            genKey : function (length = 16) {
                let random = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                let str = "";
                for (let i = 0; i < length; i++) {
                    str  = str + random.charAt(Math.random() * random.length)
                }
                return str;
            },

            //加密
            encrypt : function (plaintext,key) {
                if (plaintext instanceof Object) {
                    //JSON.stringify
                    plaintext = JSON.stringify(plaintext)
                }
                let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(plaintext), CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
                return encrypted.toString();
            },

            //解密
            decrypt : function (ciphertext,key) {
                let decrypt = CryptoJS.AES.decrypt(ciphertext, CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
                let decString = CryptoJS.enc.Utf8.stringify(decrypt).toString();
                if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
                    //JSON.parse
                    decString = JSON.parse(decString);
                }
                return decString;
            }
        };
    </script>
    <script>
        //rsaUtil
        /**
         * 简单封装一下
         */
        var rsaUtil = {
            //RSA 位数，这里要跟后端对应
            bits: 1024,

            //当前JSEncrypted对象
            thisKeyPair: {},

            //生成密钥对(公钥和私钥)
            genKeyPair: function (bits = rsaUtil.bits) {
                let genKeyPair = {};
                rsaUtil.thisKeyPair = new JSEncrypt({default_key_size: bits});

                //获取私钥
                genKeyPair.privateKey = rsaUtil.thisKeyPair.getPrivateKey();

                //获取公钥
                genKeyPair.publicKey = rsaUtil.thisKeyPair.getPublicKey();

                return genKeyPair;
            },

            //公钥加密
            encrypt: function (plaintext, publicKey) {
                if (plaintext instanceof Object) {
                    //1、JSON.stringify
                    plaintext = JSON.stringify(plaintext)
                }
                publicKey && rsaUtil.thisKeyPair.setPublicKey(publicKey);
                return rsaUtil.thisKeyPair.encrypt(plaintext);
            },

            //私钥解密
            decrypt: function (ciphertext, privateKey) {
                privateKey && rsaUtil.thisKeyPair.setPrivateKey(privateKey);
                let decString = rsaUtil.thisKeyPair.decrypt(ciphertext);
                if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
                    //JSON.parse
                    decString = JSON.parse(decString);
                }
                return decString;
            }
        };

    </script>
    <script th:inline="javascript">
        let keyPair = rsaUtil.genKeyPair();
        var publicKey1 = [[${publicKey1}]];
        var privateKey1 = [[${privateKey1}]];
    </script>
    <script>
        var publicKey2 = keyPair.publicKey;
        var privateKey2 = keyPair.privateKey;
        let aesKey2 = aesUtil.genKey();
    </script>
</head>
    <body>
    <center>后端公钥：<input id="publicKey1" th:value="${publicKey1}" /></center>
    <br />
    <center>后端私钥：<input id="privateKey1" th:value="${privateKey1}" /></center>
    <br />
    <center>后端aesKey：<input id="aesKey1" th:value="${aesKey1}" /></center>
    <br />
    <center>前端公钥：<p id="publicKey2"></p></center>
    <br />
    <center>前端私钥：<p id="privateKey2"></p></center>
    <br />
    <center>前端aesKey：<p id="aesKey2"></p></center>
    <br />
    <br />

    <center><input id="value">
    <button onclick="send()">发送</button></center>

    <br />
    <center><button onclick="myFunction()">显示前端密钥</button></center>
<script>
    function myFunction()
    {
        x=document.getElementById("publicKey2");  // 找到元素
        x.innerHTML=publicKey2;    // 改变内容
        y=document.getElementById("privateKey2");  // 找到元素
        y.innerHTML=privateKey2;    // 改变内容
        z=document.getElementById("aesKey2");  // 找到元素
        z.innerHTML=aesKey2;    // 改变内容
    }
</script>

    <script>

        function send() {
            var value = $("#value").val();
            var url = "http://localhost:8080/test";
            //将数据用aes进行加密
            var message = aes(value);
            var data = {
                "message":message,
                "publicKey2":publicKey2,
                //将aes的key用rsa进行加密
                "aesKey":rsa(aesKey2)
            }
            $.ajax({
                url: url,
                data: JSON.stringify(data),
                type: 'post',
                contentType:'application/json;charset=UTF-8,',
                dataType:'json',
                success:function (result) {
                    if (result.flag){
                        //后端解密成功
                        alert(result.message);
                        var data = result.data;
                        //用rsa解密后端传过来的用rsa加密的aesKey
                        let aesKey = rsaUtil.decrypt(data.aesKey,keyPair.privateKey);
                        //用得到的明文aesKey解密后端穿过来的数据
                        let value = aesUtil.decrypt(data.message,aesKey);

                        alert('前端解密后端密文成功，value：'+value);
                    }else{
                        alert(result.message);
                    }
                }
            })
            /*
            //RSA公钥加密
            let ciphertext = rsaUtil.encrypt(value,keyPair.publicKey);
            //私钥解密
            let plaintext = rsaUtil.decrypt(ciphertext,keyPair.privateKey);
            console.log("秘钥：");
            console.log(keyPair.privateKey);
            console.log("公钥：" + keyPair.publicKey);
            console.log("加密前：" + value);
            console.log("公钥加密后：" + ciphertext);
            console.log("解密后：" + plaintext);
            */

            /*
            Aes
            //字符串
            let text = "huanzi.qch@qq.com:欢子";
            //key
            let genKey = aesUtil.genKey();
            //key加密
            let ciphertext = aesUtil.encrypt(text,genKey);
            //key解密
            let plaintext = aesUtil.decrypt(ciphertext,genKey);

            console.log("key：");console.log(genKey);
            console.log("加密前：");console.log(text);
            console.log("key加密后：" + ciphertext);
            console.log("key解密后：");console.log(plaintext);
            */
        }
        /*
        rsa加密
        */
        function rsa (str) {
            let en = new JSEncrypt();
            en.setPublicKey(publicKey1);
            return en.encrypt(str)
        }
        /*
        aes加密
        */
        function aes (str) {
            return aesUtil.encrypt(str,aesKey2);
        }

        function sendComplex() {
            /*
            //RES复杂对象
            let user = {username: "欢子", password: 123456, remark: "abcd!@#$:"};
            //key
            let genKey = aesUtil.genKey();
            //key加密
            let ciphertext = aesUtil.encrypt(user,genKey);
            //key解密
            let plaintext = aesUtil.decrypt(ciphertext,genKey);

            console.log("key：");console.log(genKey);
            console.log("加密前：");console.log(user);
            console.log("key加密后：" + ciphertext);
            console.log("key解密后：");console.log(plaintext);
            */

            /*
            //Rsa复杂对象
            let user = {username:"欢子",password:123456,remark:"abcd!@#$:"};
            //秘钥对
            let keyPair = rsaUtil.genKeyPair();
            //公钥加密
            let ciphertext = rsaUtil.encrypt(user,keyPair.publicKey);
            //私钥解密
            let plaintext = rsaUtil.decrypt(ciphertext,keyPair.privateKey);

            console.log("秘钥：");console.log(keyPair.privateKey);
            console.log("公钥：" + keyPair.publicKey);
            console.log("加密前：" + user);
            console.log("公钥加密后：" + ciphertext);
            console.log("解密后：" + plaintext);
            */
        }
    </script>

    </body>
</html>